<?php

/**
 *  Coinpal
 */

namespace app\api\controller;

use app\api\service\CoinPal as ServiceCoinPal;
use think\facade\Config;
use think\facade\Log;
use think\facade\Request;

class CoinPal extends BaseController
{


    /**
     *  支付异步通知
     */
    public function notify()
    {
        // 获取回调数据
        $notifyData = Request::post();
        array_walk_recursive($notifyData, function (&$value) {
            if (is_string($value)) {
                $value = trim($value);
            }
        });

        // 记录回调信息
        $log_dir = root_path() . 'runtime/log/' . date("Ym") . '/coinpal';
        if (!is_dir($log_dir)) {
            mkdir($log_dir, 0755, true);
        }

        $log_path = $log_dir . '/callback_data_' . date("d") . '.log';

        // 构建详细的日志内容
        $log_data = [
            'timestamp' => date("Y-m-d H:i:s"),
            'request_id' => uniqid(),
            'client_ip' => Request::ip(),
            'user_agent' => Request::header('User-Agent'),
            'request_method' => Request::method(),
            'request_url' => Request::url(true),
            'headers' => Request::header(),
            'post_data' => $notifyData,
            'raw_input' => file_get_contents('php://input'),
            'request_size' => strlen(file_get_contents('php://input')) . ' bytes'
        ];

        $log_content = str_repeat('=', 80) . PHP_EOL;
        $log_content .= "[{$log_data['timestamp']}] CoinPal回调请求 - ID: {$log_data['request_id']}" . PHP_EOL;
        $log_content .= "客户端IP: {$log_data['client_ip']}" . PHP_EOL;
        $log_content .= "请求方式: {$log_data['request_method']}" . PHP_EOL;
        $log_content .= "请求URL: {$log_data['request_url']}" . PHP_EOL;
        $log_content .= "User-Agent: {$log_data['user_agent']}" . PHP_EOL;
        $log_content .= "数据大小: {$log_data['request_size']}" . PHP_EOL;
        $log_content .= "POST数据: " . json_encode($notifyData, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT) . PHP_EOL;
        $log_content .= "原始输入: {$log_data['raw_input']}" . PHP_EOL;
        $log_content .= "请求头信息: " . json_encode($log_data['headers'], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT) . PHP_EOL;

        file_put_contents($log_path, $log_content . PHP_EOL, FILE_APPEND | LOCK_EX);

        if (empty($notifyData)) {
            $this->logResponse($log_path, 'fail', 'Invalid signature', 400);
            return json(['status' => 'fail', 'message' => 'Invalid signature'], 400);
        }


        // 验证回调数据的签名
        if (!$this->isValid($notifyData) && env('APP_ENV') == 'prod') {
            $this->logResponse($log_path, 'fail', 'Invalid signature', 400);
            return json(['status' => 'fail', 'message' => 'Invalid signature'], 400);
        }

        // 处理回调数据
        $CoinPal = new ServiceCoinPal();
        $result = $CoinPal->handlePaymentCallbacks($notifyData);
        if ($result['code'] == 0) {
            $this->logResponse($log_path, 'success', $result['message'], 200);
            return json(['status' => 'success']);
        } else {
            $this->logResponse($log_path, 'fail', 'Processing error ' . $result['message'], 500);
            return json(['status' => 'fail', 'message' => 'Processing error. ' . $result['message']], 500);
        }
    }

    /**
     * @describe 同步支付通知
     * @author: Bobo
     * @date: 2025-04-29 17:15:00 
     * @param [type] @required
     * @return Renderable
     */
    public function redirect()
    {
        $data = Request::post();
        $CoinPal = new ServiceCoinPal();
        file_put_contents(date("d-H-i-s") . 'callback-data.log', json_encode($data));
        $result = $CoinPal->handlePaymentCallbacks($data);
        if ($result) {
            return json(['code' => 0, 'message' => 'success', 'data' => true],);
        } else {
            return json(['code' => 1, 'message' => 'Processing error', 'data' => false],);
        }
    }

    /**
     * 记录响应日志
     * @param string $log_path 日志文件路径
     * @param string $status 响应状态
     * @param string $message 响应消息
     * @param int $code HTTP状态码
     */
    private function logResponse($log_path, $status, $message, $code)
    {
        $response_log = "响应状态: {$status}" . PHP_EOL;
        $response_log .= "响应消息: {$message}" . PHP_EOL;
        $response_log .= "HTTP状态码: {$code}" . PHP_EOL;
        $response_log .= "处理时间: " . date("Y-m-d H:i:s") . PHP_EOL;
        $response_log .= str_repeat('-', 80) . PHP_EOL . PHP_EOL;

        file_put_contents($log_path, $response_log, FILE_APPEND | LOCK_EX);
    }

    /**
     *   验证回调数据的签名
     * @param $notifyData
     * @return bool
     */

    public function isValid($notifyData)
    {

        $secretKey = Config::get('coinpal.apiKey');

        if (empty($notifyData) || empty($secretKey)) {
            return false;
        }

        $str = $secretKey . $notifyData['requestId'] . $notifyData['merchantNo'] . $notifyData['orderNo'] . $notifyData['orderAmount'] . $notifyData['orderCurrency'];
        $sign = hash('sha256', $str);
        if ($sign === $notifyData['sign']) {
            return true;
        }
        return false;
    }
}
